package org.lzy.shop.activity

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import com.google.android.material.textview.MaterialTextView
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivitySettingBinding
import org.lzy.shop.theme.ThemeColorSelector
import org.lzy.shop.theme.ThemeManager
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.FileManager
import org.lzy.shop.util.LanguageUtil
import org.lzy.shop.viewmodel.MineModel


/**
 * 设置
 */
class SettingActivity: BaseMvvmActivity<ActivitySettingBinding, MineModel>({ ActivitySettingBinding.inflate(it) }) {
    private  var themeColorSelector: ThemeColorSelector?=null
    // 字体大小倍率数组 (小:0.8, 默认:1.0, 大:1.2, 超大:1.4)
    private val fontScaleArray = floatArrayOf(0.8f, 0.9f, 1.0f, 1.2f, 1.4f)
    private val fontSizeTitles = arrayOf(
        R.string.small_font_size,
        R.string.medium_font_size,
        R.string.default_font_size,
        R.string.large_font_size,
        R.string.extra_large_font_size
    )

    override fun initView() {
        setTitleText(getResString(R.string.setting))

    }

    override fun initData() {

        updateCacheSize()
        val language =DataStoreUtils.getString(Constant.SP_LANGUAGENAME)
        binding.lauageName.text=language

        val nightMode = DataStoreUtils.getString(Constant.SP_NIGHTMODE)
        if (nightMode == "night") {
            binding.nightSw.isChecked=true

        } else if (nightMode == "light") {
            binding.nightSw.isChecked=false
        }
        // 初始化字体大小设置
        initFontSizeSetting()
    }

    private fun initFontSizeSetting() {
        // 从MMKV中获取保存的字体大小索引，如果没有保存过，默认为2（默认大小）
        val savedFontIndex = DataStoreUtils.getInt(Constant.SP_FONT_SIZE_INDEX, 2)
        binding.fontSizeSeekbar.value = savedFontIndex.toFloat()
        updateFontSizePreview(savedFontIndex)
        updateFontSizeText(savedFontIndex)

        // 设置Silder的监听事件
        binding.fontSizeSeekbar.addOnChangeListener { slider, value, fromUser ->
            if (fromUser) {
                val progress = value.toInt()
                updateFontSizePreview(progress)
                updateFontSizeText(progress)

                // 保存字体大小设置
                DataStoreUtils.putInt(Constant.SP_FONT_SIZE_INDEX, progress)
                // 更新ThemeManager中的字体大小设置 - 修复参数类型错误
                ThemeManager.setFontScale(progress) // 使用索引值而不是缩放比例
                // 立即应用字体大小更改到当前Activity
                applyFontSizeChange()
            }
        }
    }

    // 应用字体大小更改到当前Activity
    private fun applyFontSizeChange() {
        // 调用ThemeManager的公共方法来应用字体大小
        ThemeManager.applyFontSizeToActivity(this)
    }

    // 递归应用字体大小到所有视图
    private fun applyFontSizeToView(view: View?) {
        if (view == null) return

        // 应用字体大小到TextView及其子类
        if (view is TextView) {
            // 保存原始字体大小，避免重复缩放
            val originalSize = view.getTag(R.id.original_text_size) as? Float ?: view.textSize / ThemeManager.getCurrentFontScale()
            view.setTag(R.id.original_text_size, originalSize)
            view.textSize = originalSize / view.resources.displayMetrics.scaledDensity * ThemeManager.getCurrentFontScale()
        }
        // 递归处理ViewGroup的子视图
        else if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                applyFontSizeToView(view.getChildAt(i))
            }
        }
    }

    override fun requestData() {

    }


    override fun onResume() {
        super.onResume()

    }

    override fun allClick() {
        //夜间模式
        binding.nightSw.setOnCheckedChangeListener { compoundButton, isChecked ->
            if (isChecked) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                DataStoreUtils.putString(Constant.SP_NIGHTMODE,"night")
            }else{
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                DataStoreUtils.putString(Constant.SP_NIGHTMODE,"light")
            }
        }

        //缓存显示以及清除
        binding.cacheLayout.setOnClickListener {
            clearCache()
        }
        //多语言修改
        binding.chooseLauauge.setOnClickListener {
            CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_lanuage) {
                override fun onBind(dialog: CustomDialog?, v: View?) {
                    val chinese = v?.findViewById<MaterialTextView>(R.id.chinese)
                    val english = v?.findViewById<MaterialTextView>(R.id.english)
                    val btnCancel = v?.findViewById<MaterialTextView>(R.id.cancel)
                    //中文
                    chinese?.setOnClickListener {
                        dialog?.dismiss()
                        binding.lauageName.text=chinese.text.toString()
                        switchLanguage("zh")
                    }
                    //Endlish
                    english?.setOnClickListener {
                        dialog?.dismiss()
                        binding.lauageName.text=english.text.toString()
                        switchLanguage("en")
                    }

                    btnCancel?.setOnClickListener { dialog?.dismiss() }
                }
            }).setMaskColor("#4D000000".toColorInt())
        }
        //关于
        binding.aboutLayout.setOnClickListener {
            startActivity(AboutActivity::class.java)
        }
        // 选择主题
        binding.chooseTheme.setOnClickListener {
            // 创建主题颜色选择器
            themeColorSelector = ThemeColorSelector(this) {(id, name, colorValue) ->
                // 主题应用后的回调处理
                Log.d("MainActivity", "Theme applied: $name (#${Integer.toHexString(colorValue)})")
                // 这里可以添加额外的UI更新逻辑
            }
            //显示颜色选择器
            themeColorSelector?.show()

            /**
             * 应用保存的主题
             * * 在你的Activity布局中添加一个主题选择按钮，并为需要应用主题的视图添加相应的tag
             *  * 如主题按钮: android:tag="theme_button"
             *  * 主题文本: android:tag="theme_text"
             *  * 主题图标: android:tag="theme_icon"
             *  * 主题背景: android:tag="theme_background"
             */
            val savedColor = ThemeManager.getCurrentThemeColor()
            if (savedColor != 0) {
                ThemeManager.applyThemeToActivity(this, savedColor)

            }

        }
        //修改密码
        binding.changePasswordLayout.setOnClickListener {
            startActivity(ForgetPwdActivity::class.java)
        }
        //更换手机号
        binding.bindPhoneLayout.setOnClickListener {
            startActivity(ChangeMobileActivity::class.java)
        }
        //退出账户
        binding.ivLoginOut.setOnClickListener {
            CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_common) {
                override fun onBind(dialog: CustomDialog?, v: View?) {
                    val showText = v?.findViewById<TextView>(R.id.txt_msg)
                    showText?.text = getResString(R.string.login_out_hint)
                    val btnOk = v?.findViewById<MaterialTextView>(R.id.btn_pos)
                    val btnCancel = v?.findViewById<MaterialTextView>(R.id.btn_neg)
                    btnOk?.setOnClickListener {
                        dialog?.dismiss()
                        DataStoreUtils.clearAll()
                        DataStoreUtils.remove(Constant.USERID)
                        DataStoreUtils.remove(Constant.MOBILE)
                        startActivity(LoginActivity::class.java)
                        finish()
                    }
                    btnCancel?.setOnClickListener { dialog?.dismiss() }
                }
            }).setMaskColor("#4D000000".toColorInt())

        }
        //隐私条款
        binding.privacyPolicyLayout.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(WebViewActivity.KEY_TITLE, getResString(R.string.privacy_policy))
            intent.putExtra(WebViewActivity.KEY_LOCAL_FILE, WebViewActivity.FILE_PRIVACY_POLICY)
            startActivity(intent)
        }
        //服务条款
        binding.termsOfServiceLayout.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(WebViewActivity.KEY_TITLE, getResString(R.string.terms_of_service))
            intent.putExtra(WebViewActivity.KEY_LOCAL_FILE, WebViewActivity.FILE_TERMS_OF_SERVICE)
            startActivity(intent)
        }
    }

    /**
     * 切换语言
     * 参考https://juejin.cn/post/6984705647879127070
     */
    private fun switchLanguage(language: String){
        // 如果是android 7.0及以上系统，直接把我们想要切换的语言类型保存在SharedPreferences中即可
        // 这里，请读者使用SharePreference保存要更改的语言内容，关键字A，同上
        // 类似putString("A", language), 详细SharePreference设置请读者另行查找解决方案

        // 如果是android 7.0以下，我们只需要调用changeAppLanguage方法即可
        LanguageUtil.changeAppLanguage(applicationContext, language)
        //本地保存要切换的语言
        DataStoreUtils.putConfig(Constant.SP_LANGUAGE,language)
        //根据本地保存的语言显示当前语言文字，如简体中文，English
        if (language=="zh") {
            DataStoreUtils.putConfig(Constant.SP_LANGUAGENAME,getResString(R.string.chinese))
        }
        if (language=="en") {
            DataStoreUtils.putConfig(Constant.SP_LANGUAGENAME,getResString(R.string.english))
        }
        // 结束当前页面，重启至首页，以刷新显示修改后的语言
        finish()
        val it = Intent(this, MainActivity::class.java)
        // 清空任务栈确保当前打开activit为前台任务栈栈顶
        // Intent.FLAG_ACTIVITY_CLEAR_TASK需搭配Intent.FLAG_ACTIVITY_NEW_TASK食用
        it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(it)

    }

    /**
     * 清理缓存
     */
    private fun clearCache() {
        showLoading()
        lifecycleScope.launch {
            FileManager.clearCache(this@SettingActivity)
            delay(500)
            dismissLoading()
            showSuccessToast("已清除缓存")
            updateCacheSize()
        }
    }

    /**
     * 更新缓存大小
     */
    private fun updateCacheSize() {
        val size = FileManager.getCacheSize(this)
        val cacheShow= StringBuilder()
        cacheShow.append(size)
        binding.cacheSize.text=cacheShow.toString()
    }

    // 更新字体大小预览
    private fun updateFontSizePreview(progress: Int) {
        val scale = fontScaleArray[progress]
        binding.fontSizePreview.textSize = 16 * scale // 使用16sp作为基准大小
    }

    // 更新字体大小文本
    private fun updateFontSizeText(progress: Int) {
        binding.fontSizeValue.text = getResString(fontSizeTitles[progress])
    }


}